import { HttpClient, HttpHeaders } from '@angular/common/http';
import { DgControl, FormBasicService } from '@farris/designer-services';
import { DesignerEnvType } from '@farris/designer-services';
import { of, Subject } from 'rxjs';
import { switchMap } from 'rxjs/operators';

/**
 * 控件工具箱：获取现有控件
 */
export class ControlCategoryService {
    /** 保存工具箱中的模板类控件 */
    static componentTemplates = [];

    constructor(private http: HttpClient, private formBasicService: FormBasicService) { }

    /**
     * farris控件+组件模板
     */
    public getControlCategoryList() {
        const subject = new Subject<any>();

        let controlCategoryList = [];

        this.getControlsInControlBox().pipe(
            switchMap(farrisControls => {
                controlCategoryList = controlCategoryList.concat(farrisControls);
                return this.getCustomTemplates();
            })
        ).subscribe((portletCategory) => {
            if (portletCategory) {
                controlCategoryList.push(portletCategory);
            }

            subject.next(controlCategoryList);
        });

        return subject;
    }

    /**
     * 获取控件列表，仅farris控件
     * @param type 控件类型
     */
    private getControlsInControlBox() {
        const subject = new Subject<any>();
        this.http.get<any[]>(`assets/form/controlList.json?version=202307`).subscribe(data => {
            if (data && data.length) {
                // 配置控件图标
                data.forEach(category => {
                    category.items.forEach(item => {
                        const icon = DgControl[item.type] && DgControl[item.type].icon;
                        if (item.icon && item.iconSource) {
                            item.controlIconClass = 'mt-2 mb-1 f-icon ' + item.icon;
                        } else {
                            item.controlIconClass = 'fd-i-Family fd_pc-' + (item.icon || icon);
                        }

                        if (item.feature) {
                            item.feature = JSON.stringify(item.feature);
                        }
                    });
                });

                subject.next(data);
            }
        });

        return subject;
    }

    /**
     * 获取定制模板
     */
    private getCustomTemplates() {
        if (this.formBasicService && this.formBasicService.envType !== DesignerEnvType.noCode) {
            return of(null);
        }
        const subject = new Subject<any>();
        const headerOption = {
            headers: new HttpHeaders({ 'Content-Type': 'application/json' })
        }
        const url = '/api/dev/formdesigner/v1.0/field-template';

        this.http.get(url, headerOption).subscribe((templates: any[]) => {
            if (!templates || !templates.length) {
                subject.next(null);
                return;
            }
            const items = [];
            ControlCategoryService.componentTemplates = [];
            templates.forEach((template: any) => {
                if (template && template.templateDom && template.templateSource && template.bindingFields) {
                    const templateDom = JSON.parse(template.templateDom);

                    const templateSource = JSON.parse(template.templateSource);
                    const templateControlType = templateSource.templateIconType;

                    const bindingFields = JSON.parse(template.bindingFields);

                    const item = {
                        id: template.id,
                        name: template.name,
                        type: templateControlType,
                        category: 'componentTemplate',
                        controlIconClass: '',
                        templateDom: templateDom,
                        fieldType: template.templateCategory === 'input' && bindingFields && bindingFields.length ? bindingFields[0].type.name : null,
                        templateCategory: template.templateCategory,
                        bindingFields
                    }
                    const icon = DgControl[templateControlType] && DgControl[templateControlType].icon;
                    item.controlIconClass = 'fd-i-Family fd_pc-' + (icon || templateControlType);

                    ControlCategoryService.componentTemplates.push(item);

                    items.push(item);
                }

            });

            const controlBoxGroup = {
                name: '组件模板',
                type: 'componentTemplate',
                items: items
            };
            subject.next(controlBoxGroup);
        }, error => {
            subject.next(null);
        });

        return subject;
    }
}
